//新增的四句话,设置CELL格式为文本格式
HSSFCellStyle cellStyle2 = demoWorkBook.createCellStyle();
HSSFDataFormat format = demoWorkBook.createDataFormat();
cellStyle2.setDataFormat(format.getFormat("@"));
cell.setCellStyle(cellStyle2);
cell.setCellValue(cells.get(i));
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
第一段:Excel的单元格格式
图中的数据有数值、货币、时间、日期、文本等格式。这些数据格式在POI中的HSSFDataFormat类里都有相应的定义。
HSSFDataFormat是HSSF子项目里面定义的一个类。类HSSFDataFormat允许用户新建数据格式类型。HSSFDataFormat类包含静态方法static java.lang.String getBuiltinFormat(short index),它可以根据编号返回内置数据类型。另外static short getBuiltinFormat(java.lang.String format)方法则可以根据数据类型返回其编号,static java.util.List getBuiltinFormats()可以返回整个内置的数据格式列表。
在HSSFDataFormat里一共定义了49种内置的数据格式,如下面所示。
HSSFDataFormat的数据格式
内置数据类型
编号
"General"
0
"0"
1
"0.00"
2
"#,##0"
3
"#,##0.00"
4
"($#,##0_);($#,##0)"
5
"($#,##0_);[Red]($#,##0)"
6
"($#,##0.00);($#,##0.00)"
7
"($#,##0.00_);[Red]($#,##0.00)"
8
"0%"
9
"0.00%"
0xa
"0.00E+00"
0xb
"# ?/?"
0xc
"# ??/??"
0xd
"m/d/yy"
0xe
"d-mmm-yy"
0xf
"d-mmm"
0x10
"mmm-yy"
0x11
"h:mm AM/PM"
0x12
"h:mm:ss AM/PM"
0x13
"h:mm"
0x14
"h:mm:ss"
0x15
"m/d/yy h:mm"
0x16
保留为过国际化用
0x17 - 0x24
"(#,##0_);(#,##0)"
0x25
"(#,##0_);[Red](#,##0)"
0x26
"(#,##0.00_);(#,##0.00)"
0x27
"(#,##0.00_);[Red](#,##0.00)"
0x28
"_($*#,##0_);_($*(#,##0);_($* \"-\"_);_(@_)"
0x29
"_(*#,##0.00_);_(*(#,##0.00);_(*\"-\"??_);_(@_)"
0x2a
"_($*#,##0.00_);_($*(#,##0.00);_($*\"-\"??_);_(@_)"
0x2b
"_($*#,##0.00_);_($*(#,##0.00);_($*\"-\"??_);_(@_)"
0x2c
"mm:ss"
0x2d
"[h]:mm:ss"
0x2e
"mm:ss.0"
0x2f
"##0.0E+0"
0x30
"@" - This is text format
0x31
在上面表中,字符串类型所对应的是数据格式为"@"(最后一行),也就是HSSFDataFormat中定义的值为0x31(49)的那行。Date类型的值的范围是0xe-0x11,本例子中的Date格式为""m/d/yy"",在HSSFDataFormat定义的值为0xe(14)。
第二段:POI中Excel文件Cell的类型
在读取每一个Cell的值的时候,通过getCellType方法获得当前Cell的类型,在Excel中Cell有6种类型,如下面所示。 Cell的类型 CellType 说明 CELL_TYPE_BLANK 空值 CELL_TYPE_BOOLEAN 布尔型 CELL_TYPE_ERROR 错误 CELL_TYPE_FORMULA 公式型 CELL_TYPE_STRING 字符串型 CELL_TYPE_NUMERIC 数值型 一般都采用CELL_TYPE_STRING和CELL_TYPE_NUMERIC类型,因为在Excel文件中只有字符串和数字。如果Cell的Type为CELL_TYPE_NUMERIC时,还需要进一步判断该Cell的数据格式,因为它有可能是Date类型,在Excel中的Date类型也是以Double类型的数字存储的。Excel中的Date表示当前时间与1900年1月1日相隔的天数,所以需要调用HSSFDateUtil的isCellDateFormatted方法,判断该Cell的数据格式是否是Excel Date类型。如果是,则调用getDateCellValue方法,返回一个Java类型的Date。